<?php
declare (strict_types=1);

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Db;

class SyncData extends Command {


    protected function configure() {
        // 指令配置
        $this->setName('sync_data')->setDescription('the sync_data command');
    }

    protected function execute(Input $input, Output $output) {

        // 指令输出
        $maxId = Db::name('board_order_record')->where('type', 1)->max('order_id');
        if (!$maxId) {
            $time = '2022-09-20 00:00:00';
        }
        $where = [];
        $where[] = ['pay_status', '=', 1];
        $where[] = ['total_fee', '>', 0];
        $where[] = ['operator_id', 'in', [407,408]];
        if ($maxId) {
            $where[] = ['id', '>', $maxId];
        }
        if (isset($time) && $time) {
            $where[] = ['created_at', '>=', $time];
        }
        $maxOrderId = Db::connect('cupboard')->table('order')->max('id');
        $where[] = ['id', '<=', $maxOrderId];
        $list = Db::connect('cupboard')->table('order')->where($where)->order('id', 'asc')->limit(100)->select();
        if (!$list) {
            $output->writeln('sync_data over');
            return;
        }
        $dataAll = [];
        foreach ($list as $key => $value) {
            $franchiserInfo = Db::connect('cupboard')->table('franchiser')->where('id', $value['franchiser_id'])->find();
            $userInfo = Db::connect('cupboard')->table('user')->where('id', $value['user_id'])->find();
            $orderRecordList = Db::connect('cupboard')->table('order_product_record')
                ->where('order_id', $value['id'])
                ->column('num');
            $num = array_sum($orderRecordList);
            $data = [
                'franchiser_id' => $value['franchiser_id'],
                'franchiser_name' => $franchiserInfo['name'],
                'user_name' => $userInfo['nickname'],
                'user_avatar' => $userInfo['avatar'],
                'buy_num' => $num,
                'buy_amount' => $value['total_fee'],
                'type' => 1,
                'order_id' => $value['id'],
                'create_time' => strtotime($value['created_at'])
            ];
            $dataAll[$key] = $data;
        }
        if (!$dataAll) {
            $output->writeln('sync_data over');
            return;
        }
        Db::name('board_order_record')->insertAll($dataAll);
        $output->writeln('sync_data over');
    }
}
